package com.goscom.app.deeset;

import com.goscom.app.database.DBAdapter;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class Address extends Activity {

	private String strMerId = "";
	private DBAdapter mDB;
	private EditText edtNumStreet, edtCity, edtCounty, edtPostCode;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.address);

		edtNumStreet = (EditText) findViewById(R.id.edtAddNumStreet);
		edtCity = (EditText) findViewById(R.id.edtAddCity);
		edtCounty = (EditText) findViewById(R.id.edtAddCounty);
		edtPostCode = (EditText) findViewById(R.id.edtAddPostCode);

		mDB = new DBAdapter(Address.this);
		mDB.open();

		getMerId();
	}

	public void getMerId() {
		try {
			strMerId = getIntent().getStringExtra("merid");
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (strMerId != null) {
			ContentValues content = new ContentValues();
			content = mDB.queryDataByMerId("ADDRESS", strMerId);
			if (content != null) {
				edtNumStreet.setText(content.getAsString("numstreet"));
				edtCity.setText(content.getAsString("city"));
				edtCounty.setText(content.getAsString("county"));
				edtPostCode.setText(content.getAsString("postcode"));
			}
		}
	}

	public void Logout(View v) {
		saveDB();
		if (mDB != null) {
			mDB.close();
		}
		startActivity(new Intent(Address.this, Login.class));
	}

	public void goPrevious(View v) {
		saveDB();
		if (mDB != null) {
			mDB.close();
		}
		startActivity(new Intent(Address.this, PersonalImformation.class)
				.putExtra("merid", strMerId));
	}

	public void goNext(View v) {
		saveDB();
		if (mDB != null) {
			mDB.close();
		}
		startActivity(new Intent(Address.this, Vehicle.class).putExtra("merid",
				strMerId));
	}

	public void Save(View v) {
		saveDB();
		Toast.makeText(Address.this, "Save Successful!", Toast.LENGTH_LONG)
				.show();
	}

	public void saveDB() {
		if (mDB.queryMerchandiser("ADDRESS", strMerId) == 0) {
			insertDB();
		} else {
			mDB.deleteData("ADDRESS", strMerId);
			insertDB();
		}
	}

	public void insertDB() {
		ContentValues content = new ContentValues();
		content.put("merid", strMerId);
		content.put("numstreet", edtNumStreet.getText().toString());
		content.put("city", edtCity.getText().toString());
		content.put("county", edtCounty.getText().toString());
		content.put("postcode", edtPostCode.getText().toString());
		mDB.insertData("ADDRESS", content);
	}

	@Override
	protected void onRestart() {
		mDB.open();
		super.onRestart();
	}

	@Override
	protected void onDestroy() {
		if (mDB != null) {
			mDB.close();
		}
		super.onDestroy();
	}
}
